import {
  getFormByProcessId,
  startProcess,
  detail,
  completeTask,
  transferTask,
  delegateTask,
  rollbackTask,
  terminateProcess,
  addMultiInstance,
  withdrawTask
} from '@/api/plugin/workflow/process'

import Layout from '@/layout/basic/index'
import defaultValues from './default-values'

import Print from '../util/print'
import Watermark from '../util/watermark'

import { mapGetters } from 'vuex'

export default {
  mixins: [defaultValues],
  computed: {
    ...mapGetters(['tag', 'userInfo', 'permission'])
  },
  data() {
    return {
      process: {}, // 流程定义/流程实例信息
      buttonList: [], // 配置按钮信息
      flow: [], // 流转信息
      userSelectType: '', // 人员选择类型 transfer转办 delegate委托 copy抄送 assignee审核人
      checkType: 'radio', // 人员选择check类型 radio单选 checkbox多选
      comment: '', // 评论
      bpmnOption: {}, // 流程图配置信息
      defaultChecked: '', // 人员选择默认选中
      waiting: true // 骨架屏加载中
    }
  },
  methods: {
    getTaskDetail(taskId, processInsId) {
      detail({ taskId, processInsId })
        .then(res => {
          console.log(res.data.data)
          const { process, form, flow, button } = res.data.data
          const { xml } = process

          const bpmnOption = {
            mode: 'view',
            xml,
            flows: this.handleResolveFlows(flow)
          }
          this.process = process
          this.flow = flow
          this.buttonList = button
          this.bpmnOption = bpmnOption

          if (this.buttonList.length > 0) {
            this.$emit('update:buttons', this.getButtons(this.buttonList))
          }
        })
        .catch(() => {})
    },
    handleResolveFlows(flow) {
      const flows = []
      flow.forEach(f => {
        let { assigneeName, createTime, endTime, comments } = f
        if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
          // safari
          createTime = createTime.replace(/-/g, '/')
          endTime = endTime.replace(/-/g, '/')
        }

        const ff = {
          id: f.historyActivityId,
          class: !endTime && f.historyActivityType != 'candidate' ? 'nodePrimary' : ''
        }
        let tooltip = ''
        if (assigneeName) {
          tooltip = `<span title='${assigneeName}'>${assigneeName}</span><br>`
          if (createTime)
            tooltip += `<span title='${createTime}'>${this.dateFormat(
              new Date(createTime),
              'YYYY-MM-DD HH:mm'
            )}</span><br>`

          if (comments && comments.length > 0) {
            let comment
            let { type, fullMessage } = comments.find(c => c.action == 'AddComment') || {}

            if (type == 'assigneeComment') {
              comment = '变更审核人：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'dispatchComment') {
              comment = '调度：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'transferComment') {
              comment = '转办：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'delegateComment') {
              comment = '委托：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'rollbackComment') {
              comment = '驳回：' + fullMessage
              ff.class = 'nodeError'
            }
            if (type == 'terminateComment') {
              comment = '终止：' + fullMessage
              ff.class = 'nodeError'
            }
            if (type == 'addMultiInstanceComment') {
              comment = '加签：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'deleteMultiInstanceComment') {
              comment = '减签：' + fullMessage
              ff.class = 'nodeError'
            }
            if (type == 'withdrawComment') {
              comment = '撤销：' + fullMessage
              ff.class = 'nodeWarn'
            }
            if (type == 'comment') {
              comment = '审批：' + fullMessage
              ff.class = 'nodeSuccess'
            }
            if (comment) tooltip += `<span title='${comment}'>${comment}</span>`
          }
          ff.tooltip = tooltip
        }

        if (f.historyActivityType == 'sequenceFlow') ff.class = 'lineWarn'
        else if (!ff.class && f.historyActivityType != 'candidate') ff.class = 'nodeSuccess'

        const index = flows.findIndex(fl => fl.id == f.historyActivityId)
        if (index != -1) flows.splice(index, 1, ff)
        else flows.push(ff)
      })
      return flows
    },
    getButtons(buttonList) {
      const buttons = []
      if (buttonList.find(b => b.buttonKey == 'wf_pass')) {
        buttons.push({
          text: '通过',
          callback: this.handleExamine(true)
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_reject')) {
        buttons.push({
          text: '驳回',
          callback: this.handleExamine(false)
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_transfer')) {
        buttons.push({
          text: '转办',
          callback: this.handleUserSelect({ type: 'transfer', checkType: 'radio' })
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_delegate')) {
        buttons.push({
          text: '委托',
          callback: this.handleUserSelect({ type: 'delegate', checkType: 'radio' })
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_rollback')) {
        buttons.push({
          text: '委托',
          callback: this.handleRollback
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_terminate')) {
        buttons.push({
          text: '终止',
          callback: this.handleTerminateProcess
        })
      }
      if (process.isMultiInstance && buttonList.find(b => b.buttonKey == 'wf_terminate')) {
        buttons.push({
          text: '加签',
          callback: this.handleUserSelect( { type: 'addInstance', checkType: 'checkbox' })
        })
      }
      if (this.permission.wf_process_withdraw && process.isOwner && process.isReturnable) {
        buttons.push({
          text: '撤销',
          callback: this.handleWithdrawTask()
        })
      }
      if (buttonList.find(b => b.buttonKey == 'wf_print')) {
        buttons.push({
          text: '打印',
          callback: this.handlePrint()
        })
      }
      return buttons
    },
    // 人员选择弹窗
    handleUserSelect({ type, checkType }) {
      if (!this.comment && ['transfer', 'delegate'].includes(type)) {
        this.$message.error('请填写批复意见')
        return
      }
      if (type == 'assignee') this.defaultChecked = this.$refs.examineForm.examineForm.assignee
      else if (type == 'copy') this.defaultChecked = this.$refs.examineForm.examineForm.copyUser

      this.$refs['user-select'].visible = true
      this.userSelectType = type
      this.checkType = checkType
    },
    // 选人回调
    handleUserSelectConfirm(id, name) {
      const { comment, copyUser } = this.$refs.examineForm.examineForm
      const { taskId, processInstanceId, processDefinitionName, processDefinitionId } = this.process

      const type = this.userSelectType
      const param = {
        taskId,
        processInstanceId,
        processDefinitionName,
        processDefinitionId,
        assignee: id,
        comment,
        copyUser
      }
      if (type == 'transfer') {
        transferTask(param).then(() => {
          // 转办
          this.$message.success('转办成功')
          this.handleCloseTag('/plugin/workflow/process/todo')
        })
      } else if (type == 'delegate') {
        // 委托
        delegateTask(param).then(() => {
          this.$message.success('委托成功')
          this.handleCloseTag('/plugin/workflow/process/todo')
        })
      } else if (type == 'addInstance') {
        // 加签
        addMultiInstance(param).then(() => {
          this.$message.success('加签成功')
        })
      } else if (type == 'copy') {
        // 抄送
        this.$refs.examineForm.examineForm.copyUser = id
        this.$refs.examineForm.examineForm.$copyUser = name
      } else if (type == 'assignee') {
        // 指定下一步审批人
        this.$refs.examineForm.examineForm.assignee = id
        this.$refs.examineForm.examineForm.$assignee = name
      }
      this.$refs['user-select'].visible = false
    },
    handleWithdrawTask() {
      const { taskId } = this.process
      this.$confirm(
        '<p><span style="color: red;">撤销：</span>撤销终止此流程</p><p><span style="color: red;">撤回：</span>撤回到发起人重新提交，若当前流程不存在发起人节点，功能同撤销</p>',
        '请选择撤销/撤回操作',
        {
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonText: '撤销',
          cancelButtonText: '撤回',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          withdrawTask({ taskId, withdrawType: 'wf_withdraw_end' }).then(() => {
            this.$message.success('操作成功')
            this.handleCloseTag('/plugin/workflow/process/todo')
          })
        })
        .catch(action => {
          if (action == 'cancel') {
            withdrawTask({ taskId, withdrawType: 'wf_withdraw_start' }).then(() => {
              this.$message.success('操作成功')
              this.handleCloseTag('/plugin/workflow/process/todo')
            })
          }
        })
    },
    handlePrint() {
      // 打印
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const option = this.deepClone(this.option)
      this.option.detail = true
      if (this.option.column) {
        this.option.column.forEach(col => {
          this.handleTemporaryPrintOption(col)
        })
      }
      if (this.option.group) {
        this.option.group.forEach(g => {
          g.column.forEach(col => {
            this.handleTemporaryPrintOption(col)
          })
        })
      }
      // 汇总表单打印
      const summaryOption = this.deepClone(this.summaryOption)
      if (this.summaryOption.group) {
        this.summaryOption.group.forEach(g => {
          g.collapse = false
          g.column.forEach(col => {
            this.handleTemporaryPrintOption(col)
          })
          setTimeout(() => {
            g.collapse = true
          })
        })
      }
      setTimeout(() => {
        loading.close()
        // const watermarkText = this.userInfo.user_name + " " + this.userInfo.dept_name
        // Watermark.set({ watermark_txt: watermarkText }) // 添加水印
        Print('#printBody')
        this.option = option
        this.summaryOption = summaryOption
        Watermark.remove() // 删除水印
      }, 500)
    },
    // 生成打印临时option
    handleTemporaryPrintOption(obj) {
      if (!obj.type) return
      obj.span = 24
      if (obj.type == 'dynamic') {
        obj.children.type = 'form'
        obj.children.column.forEach(col => {
          this.handleTemporaryPrintOption(col)
        })
      }
    },
    // 上传组件预览
    handleUploadPreview(file, column, done) {
      const { url } = file
      const { video, img } = this.$typeList
      if (video.test(url) || img.test(url)) done()
      else window.open(url)
    },
    // 审核
    handleExamine(pass) {
      this.submitLoading = true
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          const variables = {}
          this.vars.forEach(v => {
            if (v != 'comment' && this.form[v]) variables[v] = this.form[v]
          })

          this.handleCompleteTask(pass, variables)
            .then(() => {
              this.$message.success('处理成功')
            })
            .catch(() => {
              done()
              this.submitLoading = false
            })
        } else {
          done()
          this.submitLoading = false
        }
      })
    },
    /**
     * 任务审核
     * @param pass 驳回/通过
     */
    handleCompleteTask(pass, variables) {
      return new Promise((resolve, reject) => {
        const { comment, copyUser, assignee, attachment } = this.$refs.examineForm.examineForm
        if (!pass && !comment) {
          this.$message.error('请填写批复意见')
          this.submitLoading = false
          reject()
          return
        }
        const { taskId, processInstanceId, processDefinitionName, processDefinitionId } = this.process
        const param = {
          taskId,
          processInstanceId,
          processDefinitionName,
          processDefinitionId,
          pass,
          comment,
          copyUser,
          assignee,
          variables,
          attachment
        }
        completeTask(param)
          .then(() => {
            resolve()
          })
          .catch(() => {
            reject()
          })
      })
    },
    /**
     * 驳回到指定节点
     * @param nodeId 节点id
     */
    handleRollbackTask(nodeId) {
      const { taskId } = this.process
      rollbackTask({ comment: this.comment, nodeId, taskId }).then(() => {
        this.$message.success('回退成功')
        this.handleCloseTag('/plugin/workflow/process/todo')
      })
    },
    /**
     * 终止流程
     */
    handleTerminateProcess() {
      const comment = this.comment
      if (!comment) {
        this.$message.error('请填写批复意见')
        return
      }
      this.$confirm('确定要终止此流程吗?', '警告', {
        type: 'warning'
      })
        .then(() => {
          const { taskId } = this.process

          terminateProcess({ taskId, comment }).then(() => {
            this.$message.success('操作成功')
            this.handleCloseTag('/plugin/workflow/process/todo')
          })
        })
        .catch(() => {})
    }
  }
}
